package com.zto.sch.advance.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;

/**
 * @program: sch-diy-parent
 * @description:
 * @author: sch
 * @create: 2021-07-29 18:35
 **/
@RestController
@RequestMapping("excel/poi")
@Slf4j
public class POIExcelController {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private ExcelService excelService;

    /**
     * 文件上传
     * <p>1. 创建excel对应的实体对象
     * <p>2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，
     * <p>3. 直接读即可
     */
    @PostMapping("upload")
    @ResponseBody
    public String upload(@RequestParam(value = "excelFile") MultipartFile excelFile) throws IOException, InterruptedException {
        try {
            BufferedInputStream in = new BufferedInputStream(excelFile.getInputStream());
            Workbook workbook = new XSSFWorkbook(in);
            Sheet sheet = workbook.getSheetAt(0);
            AsyncTaskExecutor asyncTaskExecutor = (AsyncTaskExecutor) applicationContext.getBean("memberExecutor");
            asyncTaskExecutor.execute(() -> {
                Thread.currentThread().setName("导入客户:" + Thread.currentThread().getName());
                int count = excelService.readFilePOI(sheet);
                System.out.println("共加载了:" + count + "条数据");
            });

        } catch (Exception e) {
            log.error("报错了....", e);
            return "fail";
        }
        return "success";
    }

    @PostMapping("write")
    @ResponseBody
    public String write(@RequestParam("count") Integer count) throws IOException, InterruptedException {
        try {
            AsyncTaskExecutor asyncTaskExecutor = (AsyncTaskExecutor) applicationContext.getBean("memberExecutor");
            asyncTaskExecutor.execute(() -> {
                Thread.currentThread().setName("导入客户:" + Thread.currentThread().getName());
//                excelService.readFile(excelFile.getOriginalFilename());
            });


        } catch (Exception e) {
            log.error("报错了....", e);
            return "fail";
        }
        return "success";
    }

}
